﻿using Infragistics.WebUI.UltraWebGrid;
using System.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using uMES.LeanManufacturing.ParameterDTO;
using uMES.LeanManufacturing.ReportBusiness;

public partial class Custom_BwPlanManager_BwSynergicInfoAuditForm : BaseForm
{
    int m_PageSize = 30;
    uMESSynergicInfoBusiness synergicBal = new uMESSynergicInfoBusiness();
    uMESContainerBusiness containerBal = new uMESContainerBusiness();
    uMESCommonBusiness common = new uMESCommonBusiness();
    static string businessName = "外协管理";
    static string parentName = "Synergicinfo";

    protected void Page_Load(object sender, EventArgs e)
    {
        uMESMasterPage master = this.Master as uMESMasterPage;
        upageTurning.PageIndexChanged += new pageTurning.PageIndexChangedEventHandler(() => { SearchData(upageTurning.CurrentPageIndex); });

        if (!IsPostBack)
        {
            string type = Request["type"];
            hdType.Value = type;
            InitControl(type);

            if (type == "1")
            {
                master.strNavigation = "当前位置：外协审核-生产经理";
                master.strTitle = "外协审核-生产经理";
            }
            else if (type == "2")
            {
                master.strNavigation = "当前位置：外协审核-工艺员";
                master.strTitle = "外协审核-工艺员";
            }
            else if (type == "3")
            {
                master.strNavigation = "当前位置：外协审核-质量部门";
                master.strTitle = "外协审核-质量部门";
            }
            else if (type == "4")
            {
                master.strNavigation = "当前位置：外协审核-生产领导";
                master.strTitle = "外协审核-生产领导";
            }
            master.ChangeFrame(true);

            ClearMessage();
        }
    }

    #region 提示信息
    /// <summary>
    /// 提示信息
    /// </summary>
    /// <param name="strMessage"></param>
    /// <param name="boolResult"></param>
    protected void ShowStatusMessage(string strMessage, Boolean boolResult)
    {
        string strScript = "<script>ShowMessage(\"" + strMessage + "\", " + boolResult.ToString().ToLower() + ");</script>";
        Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, strScript);
    }

    /// <summary>
    /// 清除提示信息
    /// </summary>
    protected override void ClearMessage()
    {
        string strScript = "<script>ShowMessage(\"\", true);</script>";
        LiteralControl child = new LiteralControl(strScript);
        WebAsyncRefreshPanel1.Controls.Add(child);
    }
    #endregion

    #region 事件
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        ClearMessage();
        try { ClearData(false,true,true); SearchData(1); } catch (Exception ex) { ShowStatusMessage(ex.Message, false); }
    }

    protected void gdContainer_ActiveRowChange(object sender, Infragistics.WebUI.UltraWebGrid.RowEventArgs e)
    {
        ClearMessage();
        ClearData(false, false, true);
        LoadSpecInfo(e.Row);
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        ClearMessage();
        try
        {
            ResultModel re = SaveData(true);
            ShowStatusMessage(re.Message, re.IsSuccess);
            if (re.IsSuccess)
            {
                ClearData(false, false, true);
                SearchData(1);
            }
        }
        catch (Exception ex) { ShowStatusMessage(ex.Message, false); }
    }

    protected void txtScan_TextChanged(object sender, EventArgs e)
    {
        ClearMessage();
        SearchData(1);
    }

    protected void btnReSet_Click(object sender, EventArgs e)
    {
        Response.Redirect(Request.Url.AbsoluteUri);
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        ClearMessage();
        try
        {
            ResultModel re = SaveData(false);
            ShowStatusMessage(re.Message, re.IsSuccess);
            if (re.IsSuccess)
            {
                ClearData(false, false, true);
                SearchData(1);
            }
        }
        catch (Exception ex) { ShowStatusMessage(ex.Message, false); }
    }
    #endregion

    #region 方法
    /// <summary>
    /// 查询数据
    /// </summary>
    /// <param name="index"></param>
    void SearchData(int index)
    {
        Dictionary<string, string> para = new Dictionary<string, string>();
        para["CurrentPageIndex"] = index.ToString();
        para["PageSize"] = m_PageSize.ToString();
        para["ProcessNo"] = txtProcessNo.Text.Trim();
        para["ContainerName"] = txtContainerName.Text.Trim();
        para["ProductName"] = txtProductName.Text.Trim();
        if (!string.IsNullOrWhiteSpace(txtScan.Text.Trim()))
        {
            para["ScanContainerName"] = txtScan.Text.Trim();
        }
        para["Status"] = hdType.Value;
        uMESPagingDataDTO result = synergicBal.GetSynergicAuditData(para);
        this.gdContainer.DataSource = result.DBTable;
        this.gdContainer.DataBind();

        //给分页控件赋值，用于分页控件信息显示
        this.upageTurning.TotalRowCount = int.Parse(result.RowCount);
        this.upageTurning.RowCountByPage = m_PageSize;
    }

    ///清除数据
    void ClearData(bool isCondition, bool isGrid, bool isDetail)
    {
        if (isCondition)
        {
            txtScan.Text = ""; txtContainerName.Text = "";
            txtProcessNo.Text = ""; txtProductName.Text = "";
        }
        if (isGrid)
        {
            gdContainer.Rows.Clear();
        }
        if (isDetail)
        {
            gdSpec.Rows.Clear();
        }
    }

    /// <summary>
    /// 提交数据
    /// </summary>
    /// <returns></returns>
    ResultModel SaveData(bool isTrue)
    {
        ResultModel re = new ResultModel(false, "");
        UltraGridRow activeRow = gdContainer.DisplayLayout.ActiveRow;
        if (activeRow == null)
        {
            re.Message = "请选择批次";
            return re;
        }
        Dictionary<string, Object> conditionPara=new Dictionary<string, Object>();
        conditionPara.Add("SynergicinfoId", "'"+activeRow.Cells.FromKey("SynergicinfoId").Text+"'");
        Dictionary<string, Object> updatePara = new Dictionary<string, Object>();
        GetUpdatePara(ref updatePara, isTrue);
        re.IsSuccess = containerBal.UpdateTableByField("Synergicinfo", updatePara,conditionPara);
        if (re.IsSuccess)
        {
            #region 日志赋值
            MESAuditLog ml = new MESAuditLog();
            string ContainerID = activeRow.Cells.FromKey("ContainerID").Text;
            string ContainerName = activeRow.Cells.FromKey("ContainerName").Text;
            string AudioRoleName = string.Empty;
            if (hdType.Value == "1")
            {
                AudioRoleName = "生产经理审核";
            }
            else if (hdType.Value == "2")
            {
                AudioRoleName = "工艺员审核";
            }
            else if (hdType.Value == "3")
            {
                AudioRoleName = "质量审核";
            }
            else if (hdType.Value == "4")
            {
                AudioRoleName = "生产领导审核";
            }
            ml.ParentID = conditionPara["SynergicinfoId"].ToString().Replace("'","");//主键
            ml.ParentName = parentName;//表名
            ml.CreateEmployeeID = UserInfo["EmployeeID"];//人员ID
            ml.BusinessName = businessName;//模块名
            ml.OperationType = 1;//操作类型
            ml.Description ="外协审核:"+ AudioRoleName+(isTrue?"同意":"不同意");//说明
            ml.ContainerID = ContainerID;
            ml.ContainerName = ContainerName;
            common.SaveMESAuditLog(ml);
            #endregion
            re.Message = "保存成功";
        }
        return re;
    }

    /// <summary>
    /// 获取要更新的信息
    /// </summary>
    /// <param name="updatePara"></param>
    void GetUpdatePara(ref Dictionary<string, Object> updatePara,bool isTrue) {
        if(!isTrue)
            updatePara.Add("Isuse", "1");
        if (hdType.Value == "1")//生产经理审核
        {
            updatePara.Add("MfgManagerAuditID", "'" + UserInfo["EmployeeID"] + "'");
            updatePara.Add("MfgManagerAuditDate", "sysdate");
            if(isTrue)
                updatePara.Add("ToFactoryID", "'" + ddlSynergicCompany.SelectedValue + "'");
            updatePara.Add("Status", "2");
        }else if (hdType.Value == "2")//工艺员审核
        {
            updatePara.Add("TechnicalAuditID", "'" + UserInfo["EmployeeID"] + "'");
            updatePara.Add("TechnicalAuditDate", "sysdate");
            updatePara.Add("Status", "3");

        }
        else if (hdType.Value == "3")//质量部门审核
        {
            updatePara.Add("QualityAuditID", "'" + UserInfo["EmployeeID"] + "'");
            updatePara.Add("QualityAuditDate", "sysdate");
            updatePara.Add("Status", "4");
        }
        else if (hdType.Value == "4")//生产领导审核
        {
            updatePara.Add("MfgLeaderAuditID", "'" + UserInfo["EmployeeID"] + "'");
            updatePara.Add("MfgLeaderAuditDate", "sysdate");
            updatePara.Add("Status", "5");
        }
    }

    /// <summary>
    /// 初始化控件信息
    /// </summary>
    void InitControl(string type)
    {
        if (type == "1") {
            dvSynergicCompany.Visible = true;
            DataTable dt = containerBal.GetTableInfo("synergiccompany", null, "");

            ddlSynergicCompany.DataTextField = "synergiccompanyname";
            ddlSynergicCompany.DataValueField = "synergiccompanyid";

            ddlSynergicCompany.DataSource = dt;
            ddlSynergicCompany.DataBind();
        }
    }

    /// <summary>
    /// 工序
    /// </summary>
    /// <param name="row"></param>
    void LoadSpecInfo(UltraGridRow row)
    {
        DataTable dt = synergicBal.GetSynergicApplySpec(row.Cells.FromKey("SynergicinfoId").Text);
        gdSpec.DataSource = dt;
        gdSpec.DataBind();
    }

    protected void gdSpec_DataBound(object sender, EventArgs e)
    {
        UltraGridRow activeRow = gdContainer.DisplayLayout.ActiveRow;
        int intQty = 0;
        if (activeRow != null)
        {
            if (activeRow.Cells.FromKey("Qty").Value != null)
            {
                intQty = Convert.ToInt32(activeRow.Cells.FromKey("Qty").Value.ToString());
            }
        }
        for (int i = 0; i < gdSpec.Rows.Count; i++)
        {
            string strSpecName = gdSpec.Rows[i].Cells.FromKey("SpecName").Value.ToString();
            gdSpec.Rows[i].Cells.FromKey("SpecNameDisp").Text = common.GetSpecNameWithOutProdName(strSpecName);

            if (gdSpec.Rows[i].Cells.FromKey("unitworktime").Value != null)
            {
                gdSpec.Rows[i].Cells.FromKey("totalworktime").Text = (intQty * Convert.ToDouble(gdSpec.Rows[i].Cells.FromKey("unitworktime").Text)).ToString();
            }
        }
    }
    #endregion

    protected void Button2_Click(object sender, EventArgs e)
    {
        try
        {
            ClearMessage();

            UltraGridRow uldr = gdContainer.DisplayLayout.ActiveRow;
            if (uldr == null)
            {
                ShowStatusMessage("请选择订单记录", false);
                //Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, "<script>alert('请选择批次记录')</script>");
                return;
            }

            DataTable poupDt = new DataTable();
            poupDt.Columns.Add("ProductID");
            poupDt.Columns.Add("WorkflowID");
            DataRow newRow = poupDt.NewRow();
            newRow["ProductID"] = uldr.Cells.FromKey("ProductID").Text;
            newRow["WorkflowID"] = uldr.Cells.FromKey("Workflowid").Text;
            poupDt.Columns.Add("ContainerID"); poupDt.Columns.Add("ContainerName");
            newRow["ContainerID"] = uldr.Cells.FromKey("ContainerID").Text;
            newRow["ContainerName"] = uldr.Cells.FromKey("ContainerName").Text;
            poupDt.Rows.Add(newRow);
            Session.Add("ProcessDocument", poupDt);
            string strScript = string.Empty;

            strScript = "<script>window.showModalDialog('../bwCommonPage/uMESDocumentViewPopupForm.aspx', '', 'dialogWidth: 700px; dialogHeight: 600px; status = no; center: Yes; resizable: NO; ')</script>";
            Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, strScript);
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }
}